/**
 * 登录页脚本
 */
define(function (require, exports, module) {
    var $ = require("jquery");
    var util = require("util");
    var md5 = require("/static_public/js/lib/md5.cmd");
    var popAd = require('/static_public/js/pop1Ad1');
    require('service/global');

    var loginController = {
        init: function () {
            this._updateVerifyCode();

            var orgName = util.getCookie("loginOrgName");
            var $orgName = $("#org_name");
            if (orgName && orgName != 'null' && !$orgName.val()) {
                $orgName.val(orgName);
            }

            var username = util.getCookie("loginUserName");
            var $userName = $("#user_name");
            if (username && username != 'null' && !$userName.val()) {
                $userName.val(username);
            }

            var remember = util.getCookie("loginRemember");
            $("#remember").prop("checked", remember === "1");

            setTimeout(function () {
                $orgName.focus().select();
            }, 0);
        },
        bind: function () {
            var self = this;

            var focusOrLogin = function (e) {
                if (e.keyCode == 0x0A || e.keyCode == 0x0D) {
                    if ($.trim(this.value)) {
                        $('#password').focus();
                        e.preventDefault();
                    } else {
                        self.login()
                    }
                }
            };

            var keypressLogin = function (e) {
                if (e.keyCode == 0x0A || e.keyCode == 0x0D) {
                    self.login()
                }
            };
            var clearCookie = function () {
                if (!$(this).is(":checked")) {

                }
            };

            $("#remember").change(clearCookie);
            $("#org_name").keypress(focusOrLogin);
            $('#user_name').keypress(focusOrLogin);
            $('#password').keypress(keypressLogin);
            $('#verify_code').keypress(keypressLogin);
            $("#js_login_form").on("submit", function (e) {
                self.login();
            });

            $("#verify_code_img").on("click", $.proxy(this._updateVerifyCode, this));
            $("#get_verify").on("click", $.proxy(this._updateVerifyCode, this));
        },
        /**
         * 更新验证码
         */
        _updateVerifyCode: function () {
            $("#verify_code_img").attr('src', G_CONFIG.api_prefix + "site/verf-code&module=login&v=" + new Date().getTime());
            $('#verify_code').focus().select();
        },
        _notifyField: function (value, $ipt, msg) {
            if (!value) {
                util.alert(msg, {
                    ok: function () {
                        setTimeout(function () {
                            $ipt.focus();
                        }, 0);
                    }
                });
                return false;
            }
            return true;
        },
        /**
         * 登录
         */
        login: function () {
            var $orgName = $("#org_name");
            var orgName = $orgName.val();
            var $userName = $("#user_name");
            var userName = $userName.val();
            var $password = $("#password");
            var password = $password.val();
            var verifyCode = $("#verify_code").val();

            if (!this._notifyField(orgName, $orgName, '请输入企业号')) {
                return;
            }
            if (!this._notifyField(userName, $userName, '请输入用户名')) {
                return;
            }
            if (!this._notifyField(password, $password, '请输入密码')) {
                return;
            }

            //记住登录账号
            var domain = document.domain;
            if ($("#remember").prop("checked")) {
                util.setCookie("loginOrgName", orgName, 7, '/', domain);
                util.setCookie("loginUserName", userName, 7, '/', domain);
                util.setCookie("loginRemember", "1", 7, '/', domain);
            } else {
                util.setCookie("loginOrgName", '', -7, '/', domain);
                util.setCookie("loginUserName", '', -7, '/', domain);
                util.setCookie("loginRemember", '', -7, '/', domain);
            }

            var $loginBtn = $("#login_btn");
            $loginBtn.text("登录中...").prop("disabled", true);

            var self = this;
            password = md5(password);
            util.myAjax({
                url: G_CONFIG.api_prefix + "site/login&kfs=" + orgName,
                type: "post",
                dataType: "json",
                data: {
                    usercode: userName,
                    password: password,
                    verfcode: verifyCode
                },
                success: function (res) {
                    if (res['retCode'] == 0) {
                        if (res.data && res.data.needVerf) {
                            self._updateVerifyCode();
                            $("#js_verify_code").show();
                        }
                        else {
                            location.href = util.getUrlPara('ret_url') || '/';
                        }
                    } else if (res['retCode'] == -1168008) {
                        window.location.href = res.data;
                    } else {
                        if (res.data && res.data.needVerf) {
                            self._updateVerifyCode();
                            $("#js_verify_code").show();
                        }
                        util.alert(res["errMsg"] || res["retMsg"] || "登录失败，请检查用户名与密码");
                    }
                },
                error: function () {
                    util.alert("登录失败，请稍后再试");
                },
                complete: function () {
                    $loginBtn.text("登录").prop("disabled", false);
                }
            })
        }
    };

    var adImg = 'http://img-dev.myscrmimg.cn/static_public/ad/2016_01/new_year_day_login.jpg';
    var animImg = 'http://img-dev.myscrmimg.cn/static_public/ad/2016_01/new_year_day_5-6.png';
    popAd.run({
        key: 'new_year_day_login',
        startTime: new Date(2016, 0, 1, 0, 0, 0, 0).getTime(),
        endTime: new Date(2016, 0, 4, 0, 0, 0, 0).getTime(),
        showPop: false,
        preLoadImages: [adImg, animImg],
        showCallback: function () {
            var $animImg = $('<img src="' + animImg + '">')
                .css({
                    position: 'absolute',
                    width: '100%',
                    top: 0
                })
                .hide();

            var $div = $('<div>');
            $div.css({
                position: 'absolute',
                top: 108,
                left: 100,
                width: 30,
                height: 47,
                overflow: 'hidden'
            });

            $div.append($animImg);
            $('#js_login_ad').append($div);


            $animImg.fadeIn(1000, function () {
                setTimeout(function () {
                    $animImg.animate({
                        top: -45
                    }, 500);
                }, 300);
            });

            $('#js_login_ad img').eq(0)
                .hide()
                .attr('src', adImg).fadeIn(1000)
        }
    });

    loginController.init();
    loginController.bind();
});